package com.example.springbootauthenticationjwt.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class JWTUtil {

    @Value("${app.secret.key}")
    private String secretKey;

    public String generateToken(String subject){
        return Jwts.builder()
                .setId("tk9931")
                .setSubject(subject)
                .setIssuer("ABC_Ltd")
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)))
                .signWith(SignatureAlgorithm.HS512, Base64.getEncoder().encode(secretKey.getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    public Claims getClaims(String token){
        return Jwts.parser().setSigningKey(Base64.getEncoder().encode(secretKey.getBytes(StandardCharsets.UTF_8)))
                .parseClaimsJws(token)
                .getBody();
    }

    public String getSubject(String token){
        Claims claims = getClaims(token);
        return claims.getSubject();
    }

    public boolean isValidToken(String token){
        return getClaims(token).getExpiration().after(new Date(System.currentTimeMillis()));
    }

    public boolean isValidToken(String token,String username){
        String tokenUsername = getSubject(token);
        return (username.equals(tokenUsername) && !isTokenExpired(token));
    }

    public boolean isTokenExpired(String token){
        return getExpirationDate(token).before(new Date(System.currentTimeMillis()));
    }

    public Date getExpirationDate(String token){
        return getClaims(token).getExpiration();
    }
}
